package com.polylink;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 *@author xiliang.xiao
 *@date 2015年3月26日 上午9:36:16
 *
 **/
public class Code {
	static Configuration cfg;
	public static void createFile(Bean bean,String outPath) throws IOException, TemplateException{
		getConfiguration();
		
	    Map<String,Object> map = new HashMap<String, Object>();
	    map.put("bean", bean);
	    createFileFromTem(map,outPath+ bean.getUpName() + ".java","Bean.java");
	    createFileFromTem(map,outPath+ bean.getName() + ".jsp","bean.jsp");
	    createFileFromTem(map,outPath+ bean.getUpName() + "Control.java","BeanControl.java");
	    createFileFromTem(map,outPath+ bean.getUpName() + "Service.java","BeanService.java");
	    createFileFromTem(map,outPath+ bean.getUpName() + "SqlProvider.java","BeanSqlProvider.java");
	    createFileFromTem(map,outPath+ "I"+bean.getUpName() + "Dao.java","IBeanDao.java");
	    createFileFromTem(map,outPath+ "I"+bean.getUpName() + "Service.java","IBeanService.java");
	    
	}
	
	private static Configuration getConfiguration() throws IOException{
		if(cfg==null){
			cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File("temp"));  
			cfg.setObjectWrapper(new DefaultObjectWrapper());
			cfg.setDefaultEncoding("UTF-8");
		}
	    
		return cfg;
	}
	
	private static void createFileFromTem(Map<String,Object> map,String fileName,String tempName) throws IOException, TemplateException{
		Writer out = new OutputStreamWriter(new FileOutputStream( fileName),"UTF-8");  
	    Template temp = cfg.getTemplate(tempName);
	    temp.process(map, out);  
	    out.flush(); 
	}
}
